<template><div class="app-container" style="padding-top: 0px">
  <el-card s>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="最近时间">
        <el-radio-group style=" margin-left: 20px;" size="mini" v-model="radio" @change="handleRq">
          <el-radio-button label="1">近1天</el-radio-button>
          <el-radio-button label="2">近1个月</el-radio-button>
          <el-radio-button label="3">近3个月</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="统计时间" prop="startDate">
        <el-date-picker v-model="valueTime" type="daterange" align="right" unlink-panels size="mini" range-separator="至"
                        :clearable="false" start-placeholder="开始日期" value-format="yyyy-MM-dd" end-placeholder="结束日期"
                        @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <div class="content-wrapper">

      <!-- Map Container -->
      <div class="map-container">
        <div class="map-header" style="height: 20px">
          <h3 style="font-size: 18px;">收信区域分布</h3>
        </div>


        <!-- Map -->
        <div class="china" ref="mapChart"></div>

        <!-- Zoom Controls -->
        <div class="zoom-controls">
          <button @click="handleZoom(1)" class="zoom-btn">+</button>
          <button @click="handleZoom(-1)" class="zoom-btn">-</button>
        </div>
      </div>

      <!-- Stats Table -->
      <div class="stats-table">
        <h3 style="font-size: 14px;color:#303133">阅读十大热区</h3>
        <table>
          <thead>
          <tr>
            <th style="font-size: 14px;color:#303133">排名</th>
            <th style="font-size: 14px;color:#303133">地区</th>
            <th style="font-size: 14px;color:#303133">数量</th>
            <th style="font-size: 14px;color:#303133">占比</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(item, index) in regionData" :key="index">
            <td style="font-size: 14px;">
                <span class="rank-badge" :class="{'top-rank': index < 3}">
                  {{ index + 1 }}
                </span>
            </td>
            <td style="font-size: 14px;">{{ item.region }}</td>
            <td style="font-size: 14px;">{{ item.count }}</td>
            <td style="font-size: 14px;"class="percentage">{{ item.percentage }}</td>
          </tr>
          </tbody>
        </table>
        <div class="table-footer">
          友情提示：部分统计数据无法解析到具体内省份位置。
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
// 导入中国地图数据并注册
import '@/api/email/china.js'
import { getOpenandClickList } from '@/api/email/sendcloud'
import { GetDayA, GetMonA, GetMonB } from '@/api/public'

export default {
  name: 'GeographicDistribution',
  data() {
    return {
      valueTime:[],
      radio: 1, //1天，1月,3月
      senderList: [],
      chart: null,
      zoom: 1,
      regionData: [],
      mapData: [],
      dataList: [],
      showSearch: true,
      dataLoaded: false,
      // 查询参数
      queryParams: {
        apiUser: null,
        startDate: null,
        endDate: null,
        apiKey: null,
        pageNum: 1,
        pageSize: 20
      },
    }
  },
  mounted() {
    console.log('=== GeographicDistribution mounted 开始执行 ===')
    console.log('getOpenandClickList函数:', getOpenandClickList)
    console.log('getOpenandClickList类型:', typeof getOpenandClickList)
    console.log('初始查询参数:', this.queryParams)
    
    // 检查函数是否存在
    if (typeof getOpenandClickList !== 'function') {
      console.error('getOpenandClickList不是一个函数！')
      return
    }
    
    // 添加简单测试
    console.log('准备调用getList...')
    this.getList();
    window.addEventListener('resize', this.resizeChart)
    
    console.log('=== GeographicDistribution mounted 执行完成 ===')
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
    if (this.chart) {
      this.chart.dispose()
    }
  },

  methods: {
    getList() {
      console.log('=== GeographicDistribution getList 开始执行 ===')
      console.log('查询参数:', this.queryParams)
      
      try {
        console.log('准备调用getOpenandClickList...')
        
        // 确保函数存在
        if (typeof getOpenandClickList !== 'function') {
          console.error('错误：getOpenandClickList不是函数')
          return
        }
        
        console.log('正在调用getOpenandClickList...')
        const promise = getOpenandClickList(this.queryParams)
        console.log('getOpenandClickList返回的Promise:', promise)
        
        promise.then(res => {
          console.log('=== getOpenandClickList 成功返回 ===')
          console.log('返回数据:', res)
          console.log('返回数据.data:', res.data)
          
          this.dataList = res.data || {}
          this.processData()
          this.dataLoaded = true
          // 数据加载完成后再初始化图表
          this.$nextTick(() => {
            this.initChart()
          })
        }).catch(error => {
          console.error('=== getOpenandClickList 执行失败 ===')
          console.error('错误信息:', error)
          console.error('错误堆栈:', error.stack)
          this.dataLoaded = true
          this.$nextTick(() => {
            this.initChart()
          })
        })
        
        console.log('getOpenandClickList调用已发起')
        
      } catch (syncError) {
        console.error('=== getList同步错误 ===')
        console.error('同步错误:', syncError)
        console.error('同步错误堆栈:', syncError.stack)
      }
    },
    
    processData() {
      console.log('=== processData 开始执行 ===')
      console.log('原始数据 this.dataList:', this.dataList)
      
      this.mapData = []
      this.regionData = []
      
      var zcount = 0;
      console.log("地理分布数据:", this.dataList)
      
      // 计算总数
      for (let key in this.dataList) {
        if (this.dataList.hasOwnProperty(key)) {
          console.log(`${key}: ${this.dataList[key]}`);
          zcount += this.dataList[key];
        }
      }
      
      console.log('总数量 zcount:', zcount)
      
      // 处理地图数据和表格数据
      for (let key in this.dataList) {
        if (this.dataList.hasOwnProperty(key)) {
          // 地图数据
          let mapItem = {
            name: key,
            value: this.dataList[key]
          };
          this.mapData.push(mapItem);

          // 表格数据
          let tableItem = {
            region: key,
            count: this.dataList[key],
            percentage: zcount > 0 ? (this.dataList[key] * 100 / zcount).toFixed(2) + '%' : '0%'
          };
          this.regionData.push(tableItem);
        }
      }
      
      // 按数量排序（降序）
      this.regionData.sort((a, b) => b.count - a.count);
      // 只取前10个
      this.regionData = this.regionData.slice(0, 10);
      
      console.log('处理后的地图数据 mapData:', this.mapData)
      console.log('处理后的表格数据 regionData:', this.regionData)
      console.log('=== processData 执行完成 ===')
    },
    
    initChart() {
      this.$nextTick(() => {
        const chartContainer = this.$refs.mapChart;
        
        if (!chartContainer) {
          console.error('地图容器未找到');
          return;
        }
        
        if (chartContainer.offsetWidth === 0 || chartContainer.offsetHeight === 0) {
          // 如果容器尺寸为零，则等待下一个事件循环再次尝试
          setTimeout(() => this.initChart(), 100);
          return;
        }
        
        // 如果已经有图表实例，先销毁
        if (this.chart) {
          this.chart.dispose();
        }
        
        try {
          this.chart = echarts.init(chartContainer)
          
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: params => {
                return `${params.name}: ${params.value || 0}条`
              }
            },
            visualMap: {
              show: false,
              min: 0,
              max: Math.max(...this.mapData.map(item => item.value), 10),
              inRange: {
                color: ['#ffffff', '#0052D9']
              }
            },
            series: [{
              type: 'map',
              map: 'china',
              roam: true,
              zoom: 1.25,
              label: {
                show: true,
                fontSize: 11,
              },
              itemStyle: {
                areaColor: '#f3f4f6',
                borderColor: '#808080',
                borderWidth: 1
              },
              emphasis: {
                label: {
                  show: true
                },
                itemStyle: {
                  areaColor: '#0052D9'
                }
              },
              data: this.mapData
            }]
          }
          
          this.chart.setOption(option)
        } catch (error) {
          console.error('初始化地图失败:', error)
        }
      });
    },
    
    handleZoom(delta) {
      if (!this.chart) return;
      
      try {
        const option = this.chart.getOption()
        if (option && option.series && option.series[0]) {
          const zoom = option.series[0].zoom || 1
          const newZoom = Math.max(0.5, Math.min(3, zoom * (1 + delta * 0.2)))
          this.chart.setOption({
            series: [{
              zoom: newZoom
            }]
          })
        }
      } catch (error) {
        console.error('缩放地图失败:', error)
      }
    },
    
    resizeChart() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    
    handleQuery() {
      console.log('=== handleQuery 执行 ===')
      console.log('当前查询参数:', this.queryParams)
      this.getList();
    },
    
    handleRq() {
      console.log('=== handleRq 开始执行 ===')
      console.log('radio值:', this.radio)
      
      if (this.radio == 1) {
        this.valueTime = [];
        this.valueTime[0] = GetDayA(1);;
        this.valueTime[1] = GetMonB();
      }else if (this.radio == 2) {
        this.valueTime = [];
        this.valueTime[0] = GetMonA(1);
        this.valueTime[1] = GetMonB();
      }else if (this.radio == 3) {
        this.valueTime = [];
        this.valueTime[0] = GetMonA(3);
        this.valueTime[1] = GetMonB();
      }

      console.log('计算后的valueTime:', this.valueTime)

      if (this.valueTime[0] == undefined || this.valueTime[1] == undefined) {
        console.log('时间参数无效，停止执行')
        this.$message.warning("请选择时间")
        return;
      }
      
      this.queryParams.startDate = this.valueTime[0]; // 直接使用字符串格式
      this.queryParams.endDate = this.valueTime[1];   // 直接使用字符串格式

      console.log('更新后的查询参数:')
      console.log('startDate:', this.queryParams.startDate);
      console.log('endDate:', this.queryParams.endDate);
      
      this.handleQuery();
      console.log('=== handleRq 执行完成 ===')
    },
    
    handleSelectChange(value) {
      this.handleQuery();
    },
  }
}
</script>

<style scoped>
.geographic-dashboard {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.export-btn {
  background: #0052D9;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-wrapper {
  padding-top: 20px;
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 20px;
}

.map-container {
  position: relative;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.china {
  width: calc(100% - 40px);
  height: 650px;
  margin: 00px;
}
.view-world-btn {
  border: 1px solid #dcdfe6;
  background: white;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.legend {
  position: absolute;
  top: 60px;
  left: 40px;
  z-index: 1;
}

.legend-gradient {
  width: 200px;
  height: 20px;
  background: linear-gradient(to right, white, #0052D9);
  border: 1px solid #dcdfe6;
}

.legend-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 4px;
  color: #606266;
}

.map-chart {
  height: 600px;
}

.zoom-controls {
  position: absolute;
  bottom: 40px;
  left: 40px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.zoom-btn {
  width: 30px;
  height: 30px;
  border: 1px solid #dcdfe6;
  background: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stats-table {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  color: #909399;
  font-weight: normal;
}

.rank-badge {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background: #f4f4f5;
  border-radius: 4px;
}

.top-rank {
  background: #ff9800;
  color: white;
}

.percentage {
  color: #0052D9;
}

.table-footer {
  margin-top: 20px;
  color: #909399;
  font-size: 12px;
}
</style>
